<template>
  <div id="addQuestionView">
    <h2>{{ updatePage ? "编辑考试" : "创建考试" }}</h2>
    <a-form :model="form" label-align="left">
      <a-form-item field="examName" label="考试名称" required>
        <a-input v-model="form.examName" placeholder="请输入考试名称" />
      </a-form-item>
      <a-form-item field="examDesc" label="考试描述">
        <a-textarea v-model="form.examDesc" placeholder="请输入考试描述" />
      </a-form-item>
      <a-form-item field="startTime" label="开始时间" required>
        <a-date-picker v-model="form.startTime" show-time />
      </a-form-item>
      <a-form-item field="endTime" label="结束时间" required>
        <a-date-picker v-model="form.endTime" show-time />
      </a-form-item>
      <a-form-item field="examPassword" label="考试密码">
        <a-input-password
          v-model="form.examPassword"
          placeholder="可选，输入考试密码"
        />
      </a-form-item>
      <a-form-item field="isPublic" label="是否公开">
        <a-switch
          v-model="form.isPublic"
          checked-value="1"
          unchecked-value="0"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" style="min-width: 200px" @click="doSubmit"
          >提交</a-button
        >
      </a-form-item>
      <a-form-item
        label="测试用例配置"
        :content-flex="false"
        :merge-props="false"
        v-if="updatePage"
      >
        <a-form-item :key="index" no-style>
          <a-table
            :ref="tableRef"
            :columns="columns"
            :data="dataList"
            :pagination="{
              showTotal: true,
              pageSize: searchParams.pageSize,
              current: searchParams.current,
              total,
            }"
            @page-change="onPageChange"
          >
            <template #optional="{ record }">
              <a-space>
                <a-button status="danger" @click="doDelete(record)"
                  >删除</a-button
                >
              </a-space>
            </template>
          </a-table>
        </a-form-item>
        <div style="margin-top: 32px">
          <a-button type="primary" @click="handleClick">添加题目</a-button>
        </div>
        <a-modal
          v-model:visible="showModal"
          title="选择数据"
          :width="900"
          :footer="null"
          centered
          :mask-closable="true"
          @cancel="showModal = false"
        >
          <!-- 关闭按钮（右上角） -->
          <span class="close-button" @click="showModal = false">×</span>

          <!-- 表单项包装表格 -->
          <a-form-item no-style>
            <a-table
              :columns="columns"
              :data="questionList"
              row-key="id"
              :pagination="{
                showTotal: true,
                pageSize: searchParams.pageSize,
                current: searchParams.current,
                questionTotal: searchParams.total,
              }"
              @page-change="onQuestionPageChange"
            >
              <template #optional="{ record }">
                <a-space>
                  <a-button type="primary" @click="doAdd(record)"
                    >添加</a-button
                  >
                </a-space>
              </template>
            </a-table>
          </a-form-item>
        </a-modal>
      </a-form-item>
      <div style="margin-top: 16px" />
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  ExamControllerService,
  ExamQuestionControllerService,
  ExamQuestionVO,
  Question,
  QuestionControllerService,
  QuestionVO,
} from "../../../generated";
import { useRoute } from "vue-router";
import message from "@arco-design/web-vue/es/message";
import { format } from "date-fns";
import router from "@/router";

const route = useRoute();
const updatePage = route.path.includes("update");

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);
const showModal = ref(false);

const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "内容",
    dataIndex: "content",
  },
  {
    title: "标签",
    dataIndex: "tags",
  },
  {
    title: "提交数",
    dataIndex: "submitNum",
  },
  {
    title: "通过数",
    dataIndex: "acceptedNum",
  },
  {
    title: "用户id",
    dataIndex: "userId",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const onQuestionPageChange = (page: number) => {
  searchQuestionParams.value = {
    ...searchQuestionParams.value,
    current: page,
  };
};

const doDelete = async (examQuestion: ExamQuestionVO) => {
  const res = await ExamQuestionControllerService.deleteExamQuestionUsingPost({
    id: examQuestion.id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadQuestionRes();
  } else {
    message.error("删除失败");
  }
};
let form = ref({
  examName: "",
  examDesc: "",
  startTime: format(new Date(), "yyyy-MM-dd'T'HH:mm:ssxxx"), // 生成符合格式的时间
  endTime: format(new Date(), "yyyy-MM-dd'T'HH:mm:ssxxx"),
  examPassword: "",
  isPublic: 0,
});

const searchParams = ref({
  examId: -1,
  pageSize: 10,
  current: 1,
});
const loadData = async () => {
  const id = route.query.id;
  if (!id) return;
  const res = await ExamControllerService.getExamVoByIdUsingGet(id as any);
  if (res.code === 0) {
    form.value = res.data as any;
    searchParams.value.examId = res.data?.id as any;
    await loadQuestionRes(); // 确保数据加载完成
  } else {
    message.error("加载失败，" + res.message);
  }
};
const loadQuestionRes = async () => {
  const res =
    await ExamQuestionControllerService.listMyExamQuestionVoByPageUsingPost(
      searchParams.value
    );
  if (res.code === 0) {
    const examQuestion = res.data.records as ExamQuestionVO[];
    dataList.value = examQuestion.map((item) => ({
      id: item.id,
      title: item.questionVO?.title,
      tags: item.questionVO?.tags,
      submitNum: item.questionVO?.submitNum,
      acceptedNum: item.questionVO?.acceptedNum,
      userId: item.questionVO?.userId,
      createTime: item.questionVO?.createTime,
    }));
    // 过滤掉 null 和 undefined
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const questionList = ref<QuestionVO[]>([]);
const searchQuestionParams = ref({
  pageSize: 10,
  current: 1,
});
const questionTotal = ref(0);
const loadQuestionData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    searchQuestionParams.value
  );
  if (res.code === 0) {
    questionList.value = res.data.records;
    questionTotal.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};
const handleClick = () => {
  showModal.value = true;
  loadQuestionData();
  loadQuestionRes();
};
const questionOrder = ref(1);
const doAdd = async (question: QuestionVO) => {
  const res = await ExamQuestionControllerService.addExamQuestionUsingPost({
    examId: searchParams.value.examId, // 确保是 number
    questionId: question.id,
    questionOrder: questionOrder.value, // 确保是 number
    score: 1,
  });
  if (res.code === 0) {
    message.success("创建成功");
    questionOrder.value = questionOrder.value + 1;
    loadQuestionRes();
    showModal.value = false;
  } else {
    message.error("创建失败，" + res.message);
  }
};

onMounted(() => {
  if (updatePage) loadData();
});

const doSubmit = async () => {
  let res;
  form.value.startTime = format(
    new Date(form.value.startTime),
    "yyyy-MM-dd'T'HH:mm:ssxxx"
  );
  form.value.endTime = format(
    new Date(form.value.endTime),
    "yyyy-MM-dd'T'HH:mm:ssxxx"
  );
  if (updatePage) {
    res = await ExamControllerService.updateExamUsingPost(form.value);
  } else {
    res = await ExamControllerService.addExamUsingPost(form.value);
  }
  if (res.code === 0) {
    message.success(updatePage ? "更新成功" : "创建成功");
    if (!updatePage) {
      window.location.href = `/examination/update?id=${res.data}`;
    }
  } else {
    message.error((updatePage ? "更新失败: " : "创建失败: ") + res.message);
  }
};
</script>

<style scoped>
#addExamView {
  max-width: 800px;
  margin: auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
